<template>
  <div>
    <div class="box" style="width: 600px;">
      <div class="box">
        文档文件: <input id="uploadImage" type="file" style="width: 300px;" placeholder="" @change="toUpload" />
      </div>
      <div>
        <el-progress style="width: 300px;height: 20px;" :text-inside="true" :stroke-width="16" :percentage="progress"></el-progress>
      </div>
    </div>
    <div class="box">
      <el-table
          :data="tableData"
          border
          style="width: 100%">
          <el-table-column
            prop="fileId"
            label="资源ID"
            width="80">
          </el-table-column>
          <el-table-column
            prop="fileName"
            label="资源名称"
            width="320">
          </el-table-column>
          <el-table-column
            prop="fileSize"
            label="资源大小"
            :formatter="formatterFileSize"
            width="180">
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="上传时间" width="180">
          </el-table-column>
          <el-table-column
            prop="fileUrl"
            label="文档地址">
          </el-table-column>
          <el-table-column label="操作" width="280">
                <template slot-scope="scope">
                  <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                  <el-button size="mini" type="primary" @click="handleMakeDownCode(scope.$index, scope.row)">生成下载码</el-button>
                </template>
              </el-table-column>
        </el-table>
    </div>

    <div style="margin: 10px;">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :current-page="pageNum"
        :page-sizes="[10, 15, 20, 30]"
        :page-size="pageSize"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        >
      </el-pagination>
    </div>
  </div>
</template>

<script>
  import OSS from 'ali-oss';
  import {getResourceList,addFileInfoToDb,getDownCodeByUrl} from '@/api/news.js'
  export default {
    name: 'ResourceVideos',
    data() {
      return {
        tableData: [],
        total: 0,
        pageSize: 10,
        pageNum: 1,
        progress: 0,
      }
    },
    mounted() {
      this.loadList()
    },
    methods: {
      loadList() {
        let param = {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          keyWord: 'report'
        }
        getResourceList(param).then(res => {
          console.log('getResourceList', res);
          if(res.code == 200) {
            this.tableData = res.data.records
            this.pageNum = res.data.current
            this.pageSize = res.data.size
            this.total = res.data.total
          }
        })
      },
      handleDelete(index, row) {
        console.log('handleDelete', row)
      },
      handleMakeDownCode(index, row) {
        let param = {
          pageNum: 1,
          url: row.fileUrl
        }
        getDownCodeByUrl(param).then(res => {
          console.log('handleMakeDownCode', res)
          if(res.code == 200) {
            let code = res.data
             this.$alert(`文档下载码：<strong>${code}</strong>`, '下载码', {
              dangerouslyUseHTMLString: true
            });
           }
        })
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`)
        this.pageNum = val
        this.loadList()
      },
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`)
        this.pageSize = val
        this.loadList()
      },
      formatterFileSize(row, column) {
        let fileSize = row.fileSize
        var arrUnit = ["B", "K", "M", "G", "T", "P"],
        		baseStep = 1024,
        		unitCount = arrUnit.length,
        		unitIndex = 0;
        	while(fileSize >= baseStep && unitIndex < unitCount - 1){
        		unitIndex++;
        		fileSize /= baseStep;
        	}
        	fileSize = fileSize.toFixed(2);
        	return fileSize + " " + arrUnit[unitIndex];
      },
      async onProgress (p, cpt) {
      // p进度条的值
        let checkpoint = cpt
        console.log(checkpoint)
        console.log(p)
        console.log(cpt)
        this.showProgress = true
        this.progress = Math.floor(p * 100)
      },
      /**
       * 生成随机文件名称
       * 规则八位随机字符，加下划线连接时间戳
       */
      getFileNameUUID() {
        function rx() {
          return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
        }
        return `${+new Date()}_${rx()}${rx()}`
      },
      toUpload() {
        let that = this
          var client = new OSS({
              region: 'oss-cn-beijing',
              accessKeyId: 'LTAI5tJim8RMq5ajmbCM8FTM',
              accessKeySecret: 'VszCfBprOlAir63RhUFdzbBNUpIOxt',
              bucket: 'kaikeba-edu'
          });
          //获取文件信息
          const files = document.getElementById("uploadImage")
          if (files.files) {
              const fileLen = document.getElementById("uploadImage").files
              const file = document.getElementById("uploadImage").files[0]
              // 生成随机文件名字
              let name = fileLen[0].name
              let temporary = name.lastIndexOf('.')
              let fileNameLength = name.length
              let fileFormat = name.substring(
                temporary + 1,
                fileNameLength
              )
              if('pdf' != fileFormat && 'PDF' != fileFormat) {
                  this.$message.error('文档格式不正确')
                  return
              }

              let fileName = 'docs/'+that.getFileNameUUID() + '.' + fileFormat
              console.log('fileName='+fileName);

              // 开始上传
              for (let i = 0; i < fileLen.length; i++) {
                  const file = fileLen[i]
                  client.multipartUpload(
                      fileName,
                      file,
                      {progress:this.onProgress}
                  ).then(function(res){
                      var str=res.res.requestUrls[0]
                      console.log("aaa:"+str.split("?")[0])
                      //生成访问地址
                      let url = 'https://upload.shenmazong.com/' + fileName;
                      console.log('url='+url);
                      let param = {
                        fileName: name,
                        fileType: 'report',
                        fileUrl: url,
                        fileSize: file.size
                      }
                      addFileInfoToDb(param).then(res => {
                        if(res.code == 200) {
                          that.$message.success('文件上传成功')
                          that.loadList()
                        }
                      })
                  }).catch((err) => {
                      console.log(err)
                  })
              }
          }
      },
    }
  }
</script>

<style scoped>
  .box {
    margin-bottom: 20px;
  }
</style>
